package leetcode.秋招.商汤;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2021/8/11 18:13
 * @description：
 */
public class Main {
    public static void main(String[] args) {

    }

    class Solution {
        /**
         * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
         *
         *
         * @param nums int整型一维数组
         * @param k int整型
         * @return int整型一维数组
         */
        public int[] topKFrequent (int[] nums, int k) {
            // write code here
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int num : nums) {
                map.put(num, map.getOrDefault(num, 0) + 1);
            }
            PriorityQueue<int[]> queue = new PriorityQueue<>((o1, o2) -> o1[1] - o2[1]);
            for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
                int num = entry.getKey();
                int count = entry.getValue();
                if (queue.size() == k) {
                    if (queue.peek()[1] < count) {
                        queue.poll();
                        queue.offer(new int[]{num, count});
                    }
                } else {
                    queue.offer(new int[]{num, count});
                }
            }
            int[] ret = new int[k];
            for (int i = 0; i < k; i++) {
                ret[i] = queue.poll()[0];
            }
            Arrays.sort(ret);
            return ret;
        }
    }
}
